﻿using Microsoft.AspNetCore.Mvc;

namespace fastdbServer.Controllers;

[Area("WebApi")]
public class BasicController : Controller
{
    public static readonly string TokenKey = "token";

    protected string UserToken
    {
        get
        {
            //先尝试从cookie里取
            Request.HttpContext.Request.Cookies.TryGetValue(TokenKey, out var token);

            //如果为空，则尝试从Url里取
            if (string.IsNullOrEmpty(token)) token = Request.HttpContext.Request.Query[TokenKey];

            return token ?? string.Empty;
        }
    }

    public TM GetService<TM>() where TM : class
    {
        return HttpContext.RequestServices.GetService(typeof(TM)) as TM;
    }


    /// <summary>
    ///     设置本地cookie
    /// </summary>
    /// <param name="key">键</param>
    /// <param name="value">值</param>
    /// <param name="minutes">过期时长，单位：分钟</param>
    protected void SetCookies(string key, string value, int minutes = 60)
    {
        HttpContext.Response.Cookies.Append(key, value, new CookieOptions
        {
            Expires = DateTime.Now.AddMinutes(minutes)
        });
    }

    /// <summary>
    ///     删除指定的cookie
    /// </summary>
    /// <param name="key">键</param>
    protected void DeleteCookies(string key)
    {
        HttpContext.Response.Cookies.Delete(key);
    }
}